import base from '@/config/base';

const mediaUrl = base.mediaUrl;
const imageDefault = base.imageDefault;
const avatarDefault = base.avatarDefault;

// 图片过滤器
export const mediaFilter = function(value, style) {
  let path = '';
  let type = style === 'video' ? 1 : 2;
  if (!value) {
    return `${mediaUrl}/${imageDefault}`;
  } else if (typeof value === 'string') {
    path = value;
  } else if (value.type && value.path) {
    path = value.path;
    type = value.type;
  }

  if (path.indexOf(mediaUrl) > -1) {
    return path
  } else if (/^https:|http:/.test(path) || path.indexOf(':') > -1) {
    return path
  } else {
    if (type === 1) {
      return `${mediaUrl}/${path}?vframe/jpg/offset/1`
    }
    return style ? `${mediaUrl}/${path}-${style}` : `${mediaUrl}/${path}`
  }
}

export const avatarFilter = function(value, style) {
  let path = '';
  let type = style === 'video' ? 1 : 2;
  if (!value) {
    return `${mediaUrl}/${avatarDefault}`;
  } else if (typeof value === 'string') {
    path = value;
  } else if (value.type && value.path) {
    path = value.path;
    type = value.type;
  }

  if (path.indexOf(mediaUrl) > -1) {
    return path
  } else if (/^https:|http:/.test(path) || path.indexOf(':') > -1) {
    return path
  } else {
    if (type === 1) {
      return `${mediaUrl}/${path}?vframe/jpg/offset/1`
    }
    return style ? `${mediaUrl}/${path}-${style}` : `${mediaUrl}/${path}`
  }
}

export const allSettled = function(funcArr) {
	return new Promise((resolve) => {
		let sttled = 0
		let result = []
		for (let index = 0; index < funcArr.length; index++) {
			const element = funcArr[index]
			element
				.then(res => {
					result[index] = {
						status: 'fulfilled',
						value: res
					}
				})
				.catch(err => {
					result[index] = {
						status: 'rejected',
						reason: err
					}
				})
				.finally(() => {
					++sttled === funcArr.length && resolve(result)
				})
		}
	})
}

export const padStart = function(targetLength, padString) {
	targetLength = targetLength >> 0;
	padString = String((typeof padString !== 'undefined' ? padString : ' '));
	if (this.length > targetLength) {
		return String(this);
	} else {
		targetLength = targetLength - this.length;
		if (targetLength > padString.length) {
			padString += padString.repeat(targetLength / padString.length);
		}
		return padString.slice(0, targetLength) + String(this);
	}
};

/**
 * 时间戳转换为想要的时间格式
 */
//时间戳转换为时间 format('yyyy-MM-dd hh:mm:ss')
//时间格式转换
export const dateFormat = function(fmt = 'yyyy-MM-dd hh:mm:ss') { //author: meizz 
	const replaceMap = {
		"M+": this.getMonth() + 1, //月份 
		"d+": this.getDate(), //日 
		"h+": this.getHours(), //小时 
		"m+": this.getMinutes(), //分 
		"s+": this.getSeconds(), //秒 
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度 
		"S": this.getMilliseconds() //毫秒 
	};
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	}
	for (let key in replaceMap) {
		let value = replaceMap[key];
		if (new RegExp("(" + key + ")").test(fmt)) {
			fmt = fmt.replace(
				RegExp.$1,
				(RegExp.$1.length == 1) ? value : (("00" + value).substr(("" + value).length))
			);
		}
	}
	return fmt;
}

export const calcRemainDay = function(dateString) {
	let result;
	const minute = 1000 * 60;
	const hour = minute * 60;
	const day = hour * 24;
	const now = new Date().getTime();
	const value = new Date(dateString).getTime();
	const diffValue = parseInt(value) - parseInt(now);
	if (diffValue < 0) {
		return 0;
	}
	const dayC = diffValue / day;
	result = Math.floor(dayC) + 1;
	return result;
}

export const downloadImage = function(url) {
	return new Promise((resolve, reject) => {
		uni.downloadFile({
			url: mediaFilter(url),
			success: res => {
				if (res.statusCode === 200) {
					uni.saveImageToPhotosAlbum({
						filePath: res.tempFilePath,
						success() {
							resolve(true);
						},
						fail() {
							reject('图片保存失败');
						}
					})
				} else {
					reject('图片下载失败');
				}
			}
		})
	})
}

export const downloadVideo = function(url) {
	return new Promise((resolve, reject) => {
		uni.downloadFile({
			url: mediaFilter(url),
			success: res => {
				if (res.statusCode === 200) {
					uni.saveVideoToPhotosAlbum({
						filePath: res.tempFilePath,
						success() {
							resolve(true);
						},
						fail() {
							reject('视频保存失败');
						}
					})
				} else {
					reject('视频下载失败');
				}
			}
		})
	})
}